<template>
  <div class="food-service-container">
    <!-- 成功提示卡片 -->
    <transition name="fade">
      <el-card v-if="showSuccessMessage" class="success-card" shadow="hover">
        <el-result
          icon="success"
          title="饮食服务记录已创建成功"
          :sub-title="`将在 ${countdown} 秒后自动返回列表页`"
        >
          <template #extra>
            <div class="success-actions">
              <el-progress type="dashboard" :percentage="countdownPercentage" :width="80">
                <span class="countdown-text">{{ countdown }}</span>
              </el-progress>
              <el-button type="primary" class="mt-4" @click="handleReturnToList">立即返回列表</el-button>
            </div>
          </template>
        </el-result>
      </el-card>
    </transition>

    <!-- 主要流程内容 -->
    <el-card v-if="!showSuccessMessage" shadow="hover" class="main-card">
      <template #header>
        <div class="process-header">
          <div class="header-left">
            <el-icon class="header-icon"><Food /></el-icon>
            <span class="header-title">创建饮食服务记录</span>
          </div>
          <div class="header-right">
            <el-button v-if="currentStepIndex > 0" type="info" plain @click="prevStep">
              <el-icon><ArrowLeft /></el-icon> 上一步
            </el-button>
            <el-button v-if="currentStepIndex < steps.length - 1" type="primary" @click="nextStep">
              下一步 <el-icon><ArrowRight /></el-icon>
            </el-button>
            <el-button v-if="currentStepIndex === steps.length - 1" type="success" @click="submitForm">
              <el-icon><Check /></el-icon> 提交
            </el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </div>
      </template>

      <!-- 步骤条展示 -->
      <div class="step-navigation">
        <el-steps :active="currentStepIndex" finish-status="success" process-status="process">
          <el-step 
            v-for="(step, index) in steps" 
            :key="index" 
            :title="step.title" 
            :description="step.description"
            :icon="step.icon"
          />
        </el-steps>
      </div>

      <!-- 步骤内容区域 -->
      <div class="step-content">
        <!-- 步骤1：选择老人 -->
        <el-collapse-transition>
          <div v-show="currentStepIndex === 0">
            <div class="step-header">
              <h3>选择服务对象</h3>
              <p class="step-description">请选择需要提供饮食服务的老人</p>
            </div>
            
            <el-card class="inner-card">
              <div class="elder-search-container">
                <el-input
                  v-model="elderSearchKeyword"
                  placeholder="输入老人姓名或身份证号搜索"
                  class="elder-search-input"
                  clearable
                  @keyup.enter="searchElder"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                  <template #append>
                    <el-button @click="searchElder">搜索</el-button>
                  </template>
                </el-input>
              </div>
              
              <el-table
                v-loading="elderLoading"
                :data="elderList"
                border
                highlight-current-row
                @row-click="handleElderSelect"
                style="width: 100%"
                class="elder-table"
              >
                <el-table-column type="index" width="50" label="#" />
                <el-table-column label="姓名" prop="elderName" min-width="80" />
                <el-table-column label="性别" width="60">
                  <template #default="scope">
                    {{ String(scope.row.gender) === '1' ? '男' : '女' }}
                  </template>
                </el-table-column>
                <el-table-column label="年龄" prop="age" width="60" />
                <el-table-column label="房间号" prop="roomNo" min-width="80">
                  <template #default="scope">
                    {{ scope.row?.roomNo || '未分配' }}
                  </template>
                </el-table-column>
                <el-table-column label="饮食禁忌" prop="dietaryRestrictions" min-width="120">
                  <template #default="scope">
                    {{ scope.row?.dietaryRestrictions || '无' }}
                  </template>
                </el-table-column>
                <el-table-column label="过敏信息" prop="allergies" min-width="120">
                  <template #default="scope">
                    {{ scope.row?.allergies || '无' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                  <template #default="scope">
                    <el-button link type="primary" @click.stop="handleElderSelect(scope.row)">选择</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <el-pagination
                v-if="elderList.length > 0"
                class="mt-3"
                layout="total, sizes, prev, pager, next"
                :total="elderTotal"
                :page-size="elderQuery.pageSize"
                :current-page="elderQuery.pageNum"
                @size-change="handleElderSizeChange"
                @current-change="handleElderCurrentChange"
              />
            </el-card>
            
            <!-- 已选择的老人信息卡片 -->
            <transition name="el-fade-in-linear">
              <el-card v-if="selectedElder" class="elder-info-card mt-4" shadow="hover">
                <template #header>
                  <div class="selected-elder-header">
                    <span>已选择的老人</span>
                    <el-button link type="danger" @click="clearSelectedElder">取消选择</el-button>
                  </div>
                </template>
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="姓名">{{ selectedElder.elderName }}</el-descriptions-item>
                  <el-descriptions-item label="性别">{{ selectedElder.gender === '1' || selectedElder.gender === 1 ? '男' : '女' }}</el-descriptions-item>
                  <el-descriptions-item label="年龄">{{ selectedElder.age }}岁</el-descriptions-item>
                  <el-descriptions-item label="房间号">{{ selectedElder.roomNo || '未分配' }}</el-descriptions-item>
                  <el-descriptions-item label="饮食禁忌" :span="2">{{ selectedElder.dietaryRestrictions || '无' }}</el-descriptions-item>
                  <el-descriptions-item label="过敏信息" :span="2">{{ selectedElder.allergies || '无' }}</el-descriptions-item>
                </el-descriptions>
              </el-card>
            </transition>
          </div>
        </el-collapse-transition>

        <!-- 步骤2：饮食服务信息 -->
        <el-collapse-transition>
          <div v-show="currentStepIndex === 1">
            <div class="step-header">
              <h3>饮食服务信息</h3>
              <p class="step-description">请填写饮食服务的基本信息</p>
            </div>
            
            <el-form ref="serviceFormRef" :model="formData" :rules="rules.serviceInfo" label-width="100px" class="service-form">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="餐食名称" prop="mealName">
                    <el-input v-model="formData.mealName" placeholder="请输入餐食名称" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="餐食类型" prop="mealType">
                    <el-select v-model="formData.mealType" placeholder="请选择餐食类型" style="width:100%">
                      <el-option label="早餐" value="0" />
                      <el-option label="午餐" value="1" />
                      <el-option label="晚餐" value="2" />
                      <el-option label="加餐" value="3" />
                      <el-option label="其它" value="4" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="用餐时间" prop="mealTime">
                    <el-date-picker
                      v-model="formData.mealTime"
                      type="datetime"
                      placeholder="选择用餐时间"
                      style="width:100%"
                      value-format="YYYY-MM-DD HH:mm:ss"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="餐食图片" prop="foodUri">
                    <image-upload v-model="formData.foodUri" :limit="1" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="食物清单" prop="foodItems">
                <el-input v-model="formData.foodItems" type="textarea" :rows="3" placeholder="请输入详细的食物清单" />
              </el-form-item>
              
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="饮食要求" prop="dietaryRequirements">
                    <el-input v-model="formData.dietaryRequirements" placeholder="特殊饮食要求" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="过敏信息" prop="allergies">
                    <el-input v-model="formData.allergies" placeholder="食物过敏信息" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="是否需要协助" prop="assistanceNeeded">
                    <el-radio-group v-model="formData.assistanceNeeded">
                      <el-radio label="0">否</el-radio>
                      <el-radio label="1">是</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="是否送餐" prop="isVisitingService">
                    <el-radio-group v-model="formData.isVisitingService">
                      <el-radio label="0">否</el-radio>
                      <el-radio label="1">是</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>

        <!-- 步骤3：服务人员与费用 -->
        <el-collapse-transition>
          <div v-show="currentStepIndex === 2">
            <div class="step-header">
              <h3>服务人员与费用</h3>
              <p class="step-description">请指定服务人员并填写相关费用</p>
            </div>
            
            <el-form ref="staffFormRef" :model="formData" :rules="rules.staffInfo" label-width="100px" class="staff-form">
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="服务人员" prop="staffId">
                    <el-select v-model="formData.staffId" placeholder="请选择服务人员" filterable @change="handleStaffChange" style="width:100%">
                      <el-option
                        v-for="staff in staffList"
                        :key="staff.staffId"
                        :label="staff.staffName"
                        :value="staff.staffId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="人员姓名" prop="staffName">
                    <el-input v-model="formData.staffName" placeholder="服务人员姓名" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="服务费用" prop="serviceFee">
                    <el-input-number v-model="formData.serviceFee" :min="0" :precision="2" style="width:100%" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="付款状态" prop="paymentStatus">
                    <el-select v-model="formData.paymentStatus" placeholder="请选择付款状态" style="width:100%">
                      <el-option label="未支付" value="未支付" />
                      <el-option label="已支付" value="已支付" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-transition>

        <!-- 步骤4：确认信息 -->
        <el-collapse-transition>
          <div v-show="currentStepIndex === 3">
            <div class="step-header">
              <h3>确认服务信息</h3>
              <p class="step-description">请确认所有信息无误后提交</p>
            </div>
            
            <el-card class="confirmation-card" shadow="hover">
              <template #header>
                <div class="confirmation-header">
                  <span>饮食服务信息确认</span>
                </div>
              </template>
              
              <el-descriptions title="基本信息" :column="2" border class="service-confirmation">
                <el-descriptions-item label="老人姓名" :span="1">{{ selectedElder?.elderName || '未知' }}</el-descriptions-item>
                <el-descriptions-item label="房间号" :span="1">{{ selectedElder?.roomNo || '未知' }}</el-descriptions-item>
                <el-descriptions-item label="餐食名称" :span="1">{{ formData.mealName || '未知' }}</el-descriptions-item>
                <el-descriptions-item label="餐食类型" :span="1">
                  {{ formData.mealType === '0' ? '早餐' :
                     formData.mealType === '1' ? '午餐' :
                     formData.mealType === '2' ? '晚餐' :
                     formData.mealType === '3' ? '加餐' : '其它' }}
                </el-descriptions-item>
                <el-descriptions-item label="用餐时间" :span="2">{{ formatDate(formData.mealTime) }}</el-descriptions-item>
                <el-descriptions-item label="食物清单" :span="2">{{ formData.foodItems || '无' }}</el-descriptions-item>
                <el-descriptions-item label="饮食要求" :span="1">{{ selectedElder?.dietaryRestrictions || formData.dietaryRequirements || '无' }}</el-descriptions-item>
                <el-descriptions-item label="过敏信息" :span="1">{{ selectedElder?.allergies || formData.allergies || '无' }}</el-descriptions-item>
                <el-descriptions-item label="是否需要协助" :span="1">{{ formData.assistanceNeeded === '1' ? '是' : '否' }}</el-descriptions-item>
                <el-descriptions-item label="是否送餐" :span="1">{{ formData.isVisitingService === '1' ? '是' : '否' }}</el-descriptions-item>
              </el-descriptions>
              
              <el-descriptions title="服务与费用信息" :column="2" border class="mt-4">
                <el-descriptions-item label="服务人员" :span="1">{{ formData.staffName }}</el-descriptions-item>
                <el-descriptions-item label="服务费用" :span="1">¥{{ formData.serviceFee }}</el-descriptions-item>
                <el-descriptions-item label="付款状态" :span="1">{{ formData.paymentStatus }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ formData.remarks || '无' }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </div>
        </el-collapse-transition>
      </div>
    </el-card>
  </div>
</template>

<script setup name="FoodServiceProcess" lang="ts">
import { ref, reactive, computed, getCurrentInstance, onMounted, onUnmounted, toRefs } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { ElForm } from 'element-plus';
import { useRouter } from 'vue-router';
import { 
  Food, Search, ArrowLeft, ArrowRight, Check, Location, User, Money
} from '@element-plus/icons-vue';

// 导入API
import { addFoodService } from '@/api/nursing/foodService';
import { listElder, getElder } from '@/api/nursing/elder';
import { addElderOutstandingFees } from '@/api/nursing/elderOutstandingFees';

// 类型导入
import type { FoodServiceForm } from '@/api/nursing/foodService/types';
import type { ElderBasicVO, ElderBasicQuery } from '@/api/nursing/elder/types';
import type { ElderOutstandingFeesForm } from '@/api/nursing/elderOutstandingFees/types';

// 使用路由
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 步骤控制
const steps = [
  {
    title: '选择老人',
    description: '选择服务对象',
    icon: User
  },
  {
    title: '服务信息',
    description: '填写饮食信息',
    icon: Food
  },
  {
    title: '人员与费用',
    description: '指定服务人员与费用',
    icon: Money
  },
  {
    title: '确认提交',
    description: '确认所有信息',
    icon: Check
  }
];
const currentStepIndex = ref(0);

// 成功提示控制
const showSuccessMessage = ref(false);
const countdown = ref(5);
let countdownTimer: number | null = null;

// 老人搜索相关
const elderSearchKeyword = ref('');
const elderLoading = ref(false);
const elderList = ref<ElderBasicVO[]>([]);
const elderTotal = ref(0);
const elderQuery = reactive<ElderBasicQuery>({
  pageNum: 1,
  pageSize: 10,
  elderName: undefined,
  idCard: undefined
});

// 定义本地接口，包含 ElderBasicVO 和额外需要的字段
interface DisplayElderInfo extends ElderBasicVO {
  roomNo?: string;
  roomId?: string | number;
  dietaryRestrictions?: string;
  allergies?: string;
}

// 将 selectedElder 的类型改为 DisplayElderInfo
const selectedElder = ref<DisplayElderInfo | null>(null);

// 服务人员列表
interface StaffInfo {
  staffId: string | number;
  staffName: string;
  position?: string;
}

const staffList = ref<StaffInfo[]>([
  { staffId: 1, staffName: '张护工', position: '护工' },
  { staffId: 2, staffName: '李营养师', position: '营养师' },
  { staffId: 3, staffName: '王服务员', position: '服务员' },
  { staffId: 4, staffName: '赵阿姨', position: '保洁员' }
]);

// 表单引用
const serviceFormRef = ref<InstanceType<typeof ElForm>>();
const staffFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const formData = reactive<FoodServiceForm>({
  elderId: undefined,
  elderName: '',
  foodUri: '',
  mealName: '',
  mealType: '',
  mealTime: '',
  foodItems: '',
  dietaryRequirements: '',
  allergies: '',
  assistanceNeeded: '0',
  isVisitingService: '0',
  roomId: undefined,
  staffId: undefined,
  staffName: '',
  serviceFee: 0,
  paymentStatus: '未支付',
  remarks: '',
  status: '0'
});

// 表单验证规则
const rules = {
  serviceInfo: {
    mealName: [{ required: true, message: '请输入餐食名称', trigger: 'blur' }],
    mealTime: [{ required: true, message: '请选择用餐时间', trigger: 'change' }],
  },
  staffInfo: {
  }
};

// 方法：格式化日期显示
const formatDate = (date: string) => {
  if (!date) return '';
  const dateObj = new Date(date);
  const year = dateObj.getFullYear();
  const month = String(dateObj.getMonth() + 1).padStart(2, '0');
  const day = String(dateObj.getDate()).padStart(2, '0');
  const hours = String(dateObj.getHours()).padStart(2, '0');
  const minutes = String(dateObj.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 倒计时百分比计算
const countdownPercentage = computed(() => {
  return (countdown.value / 5) * 100;
});

// 搜索老人
const searchElder = async () => {
  elderLoading.value = true;
  
  // 设置搜索条件
  if (elderSearchKeyword.value) {
    // 根据关键字判断是身份证还是姓名
    if (/^\d+$/.test(elderSearchKeyword.value)) {
      elderQuery.idCard = elderSearchKeyword.value;
      elderQuery.elderName = undefined;
    } else {
      elderQuery.elderName = elderSearchKeyword.value;
      elderQuery.idCard = undefined;
    }
  } else {
    elderQuery.elderName = undefined;
    elderQuery.idCard = undefined;
  }
  
  try {
    const res = await listElder(elderQuery);
    elderList.value = res.rows;
    elderTotal.value = res.total;
  } catch (error) {
    console.error('获取老人列表失败', error);
    proxy?.$modal.msgError('获取老人列表失败');
  } finally {
    elderLoading.value = false;
  }
};

// 选择老人，构造 DisplayElderInfo 对象
// 参数类型改为基础的 ElderBasicVO，因为列表数据是这个类型
const handleElderSelect = async (elder: ElderBasicVO) => {
  try {
    proxy?.$modal.loading("正在加载老人信息...");
    const res = await getElder(elder.elderId); // 获取详情
    const elderData = res.data as any; // 详情数据可能包含更多字段

    // 构造 DisplayElderInfo 对象，合并列表和详情信息
    const displayInfo: DisplayElderInfo = {
      ...elder, // 基础信息来自列表项
      roomId: elderData?.roomId, // 优先从详情获取
      roomNo: elderData?.roomNo,
      dietaryRestrictions: elderData?.dietaryRestrictions,
      allergies: elderData?.allergies
    };

    selectedElder.value = displayInfo; // 赋值给 DisplayElderInfo 类型的 ref

    // 更新表单数据，从构造好的 displayInfo 获取
    formData.elderId = displayInfo.elderId;
    formData.elderName = displayInfo.elderName;
    formData.roomId = displayInfo.roomId;
    formData.dietaryRequirements = displayInfo.dietaryRestrictions || '';
    formData.allergies = displayInfo.allergies || '';

    proxy?.$modal.closeLoading();
    proxy?.$modal.msgSuccess('已选择老人: ' + displayInfo.elderName);
  } catch (error) {
    proxy?.$modal.closeLoading();
    console.error('获取老人详情失败', error);
    proxy?.$modal.msgError('获取老人详情失败');
  }
};

// 清除选中的老人
const clearSelectedElder = () => {
  selectedElder.value = null;
  formData.elderId = undefined;
  formData.elderName = '';
  formData.roomId = undefined;
  formData.dietaryRequirements = '';
  formData.allergies = '';
};

// 处理服务人员选择变更
const handleStaffChange = (staffId: string | number) => {
  const staff = staffList.value.find(item => item.staffId === staffId);
  if (staff) {
    formData.staffName = staff.staffName;
  }
};

// 分页处理函数
const handleElderSizeChange = (val: number) => {
  elderQuery.pageSize = val;
  searchElder();
};

const handleElderCurrentChange = (val: number) => {
  elderQuery.pageNum = val;
  searchElder();
};

// 下一步
const nextStep = async () => {
  let valid = true;
  
  // 根据当前步骤进行验证
  switch (currentStepIndex.value) {
    case 0: // 选择老人
      if (!selectedElder.value) {
        proxy?.$modal.msgError('请选择一位老人');
        valid = false;
      }
      break;
    case 1: // 服务信息
      await serviceFormRef.value?.validate((isValid) => {
        valid = isValid;
      });
      break;
    case 2: // 人员与费用
      await staffFormRef.value?.validate((isValid) => {
        valid = isValid;
      });
      break;
  }
  
  if (valid) {
    currentStepIndex.value++;
  }
};

// 上一步
const prevStep = () => {
  currentStepIndex.value--;
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 5;
  showSuccessMessage.value = true;
  
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  countdownTimer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearTimerAndNavigate();
    }
  }, 1000);
};

// 清除计时器并导航
const clearTimerAndNavigate = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  router.push('/elder_service/foodService');
};

// 立即返回列表
const handleReturnToList = () => {
  clearTimerAndNavigate();
};

// 提交表单
const submitForm = async () => {
  // 手动触发所有相关表单的验证
  let serviceValid = false;
  let staffValid = false;
  await serviceFormRef.value?.validate((isValid) => { serviceValid = isValid; });
  await staffFormRef.value?.validate((isValid) => { staffValid = isValid; });

  if (!serviceValid || !staffValid) {
    proxy?.$modal.msgError('请检查表单信息是否填写完整且正确');
    return;
  }

  if (!selectedElder.value || !formData.elderId) {
    proxy?.$modal.msgError('请先选择服务的老人');
    return;
  }

  try {
    proxy?.$modal.loading("正在提交...");
    // 1. 添加饮食服务记录
    // 准备提交给 addFoodService 的数据
    const foodServicePayload: FoodServiceForm = {
      ...formData,
      mealTime: formatDateToDateTimeString(formData.mealTime), // 确保日期时间格式正确
    };
    // 移除可能存在的 agreement 属性 (虽然已从 reactive 定义中移除，保险起见)
    // delete (foodServicePayload as any).agreement;

    const response = await addFoodService(foodServicePayload);
    // 确保 response.data 存在且有 serviceId
    const serviceId = response?.data?.serviceId;

    if (!serviceId) {
      console.error('未能从 addFoodService 响应中获取 serviceId', response);
      throw new Error('创建饮食服务失败，未返回服务ID');
    }

    // 2. 如果选择了未支付状态且费用大于0，则创建欠费记录
    if (formData.paymentStatus === '未支付' && typeof formData.serviceFee === 'number' && formData.serviceFee > 0) {
      const billDate = new Date();
      const dueDate = new Date();
      dueDate.setDate(billDate.getDate() + 30); // 30天后到期

      // 准备提交给 addElderOutstandingFees 的数据
      const outstandingFeesData: ElderOutstandingFeesForm = {
        elderId: formData.elderId,
        elderName: formData.elderName,
        feeSource: '餐饮费',
        sourceId: serviceId,
        feeDescription: `饮食服务：${formData.mealName || '未知餐食'}`,
        billDate: formatDateToDateString(billDate),
        dueDate: formatDateToDateString(dueDate),
        totalAmount: formData.serviceFee,
        paidAmount: 0,
        outstandingAmount: formData.serviceFee,
        paymentStatus: '未支付',
        isOverdue: '0',
        overdueDays: 0,
        reminderCount: 0,
        remarks: formData.remarks,
        lastPaymentDate: undefined,
        paymentDeadline: undefined,
        lastReminderDate: undefined,
      };

      await addElderOutstandingFees(outstandingFeesData);
    }

    proxy?.$modal.closeLoading();
    // 显示成功信息并开始倒计时
    startCountdown();

  } catch (error) {
    proxy?.$modal.closeLoading();
    console.error('提交操作失败', error);
    // 提供更具体的错误反馈
    let errorMsg = '提交失败，请重试';
    if (error instanceof Error) {
      errorMsg = `提交失败: ${error.message}`;
    } else if (typeof error === 'string') {
      errorMsg = error;
    }
    proxy?.$modal.msgError(errorMsg);
  }
};

// 取消
const cancel = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
  showSuccessMessage.value = false;
  router.push('/elder_service/foodService');
};

// 生命周期钩子
onMounted(() => {
  searchElder();
});

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});

// 方法：格式化日期为 YYYY-MM-DD
const formatDateToDateString = (date: Date | string | null): string => {
  if (!date) return '';
  try {
    const d = new Date(date);
    if (isNaN(d.getTime())) { // 检查日期是否有效
      console.error('无效的日期:', date);
      return '';
    }
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (e) {
    console.error('日期格式化失败', e);
    return '';
  }
};

// 方法：格式化日期时间为 YYYY-MM-DD HH:mm:ss
const formatDateToDateTimeString = (date: string | Date | null): string => {
  if (!date) return '';
  try {
    const dateObj = new Date(date);
    if (isNaN(dateObj.getTime())) { // 检查日期是否有效
      console.error('无效的日期时间:', date);
      return '';
    }
    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, '0');
    const day = String(dateObj.getDate()).padStart(2, '0');
    const hours = String(dateObj.getHours()).padStart(2, '0');
    const minutes = String(dateObj.getMinutes()).padStart(2, '0');
    const seconds = String(dateObj.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error("日期时间格式化错误:", error);
    return '';
  }
};
</script>

<style scoped>
.food-service-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.success-card {
  max-width: 600px;
  margin: 40px auto;
  text-align: center;
}

.success-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.countdown-text {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.main-card {
  margin-bottom: 20px;
}

.process-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  margin-right: 10px;
  font-size: 20px;
  color: #409EFF;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.step-navigation {
  margin: 20px 0;
}

.step-content {
  padding: 20px 0;
  min-height: 400px;
}

.step-header {
  margin-bottom: 20px;
}

.step-header h3 {
  margin: 0 0 5px 0;
  color: #303133;
}

.step-description {
  color: #909399;
  margin: 0;
}

.inner-card {
  margin-bottom: 20px;
}

.elder-search-container {
  margin-bottom: 20px;
}

.elder-search-input {
  width: 100%;
  max-width: 500px;
}

.elder-table {
  margin-bottom: 15px;
}

.selected-elder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.service-form, .staff-form {
  max-width: 90%;
  margin: 0 auto;
}

.confirmation-card {
  max-width: 90%;
  margin: 0 auto;
}

.confirmation-header {
  font-weight: bold;
}

.service-confirmation {
  margin-bottom: 20px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@media (max-width: 768px) {
  .service-form, .staff-form, .confirmation-card {
    max-width: 100%;
  }
}
</style> 